package com.pm.business.controller;

import com.pm.business.domain.*;
import com.pm.business.service.*;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.entity.SysUser;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.enums.BusinessType;
import com.pm.common.utils.DictUtils;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 基本信息Controller
 * 
 * @author zxl
 * @date 2022-05-05
 */
@RestController
@RequestMapping("/business/my_bid_project")
public class MyBidProjectController extends BaseController
{
    @Autowired
    private IMyBidProjectService myBidProjectService;
    @Autowired
    private IProjectPersonService projectPersonService;
    @Autowired
    private IBidProjectPointService bidProjectPointService;
    @Autowired
    private IBidProjectProcessService bidProjectProcessService;

    /**
     * 查询基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:list')")
    @GetMapping("/list")
    public TableDataInfo list(BidProject bidProject)
    {
        //添加权限,不是超级用户就加入
        if (!SysUser.isAdmin(SecurityUtils.getUserId())){
            bidProject.setTempCreator(SecurityUtils.getUsername());
            bidProject.setTempAuditor(SecurityUtils.getUserId());
        }
        startPage();
        List<BidProject> list = myBidProjectService.selectBidProjectList(bidProject);
        return getDataTable(list);
    }
    @GetMapping("/listForOptions")
    public TableDataInfo listForOptions(BidProject bidProject)
    {
        //添加权限,不是超级用户就加入
        if (!SysUser.isAdmin(SecurityUtils.getUserId())){
            bidProject.setTempCreator(SecurityUtils.getUsername());
            bidProject.setTempAuditor(SecurityUtils.getUserId());
        }
        List<BidProject> list = myBidProjectService.selectBidProjectList(bidProject);
        return getDataTable(list);
    }

    /**
     * 导出基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:export')")
    @Log(title = "基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BidProject bidProject)
    {
        List<BidProject> list = myBidProjectService.selectBidProjectList(bidProject);
        ExcelUtil<BidProject> util = new ExcelUtil<BidProject>(BidProject.class);
        util.exportExcel(response, list, "基本信息数据");
    }

    /**
     * 获取基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId)
    {
        BidProject bidProject= myBidProjectService.selectBidProjectByProjectId(projectId);
        List<ProjectPerson>projectPersonList = new ArrayList<>();
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){
            List<Long>personIdList =new ArrayList<>();
            Map<Long,String>idTypeMap = new HashMap<>();
            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = new ArrayList<>();
                selectedPerson.add(cppm.getPersonType());
                selectedPerson.add(cppm.getPersonId()+"");
                cppm.setSelectedPerson(selectedPerson);
                personIdList.add(cppm.getPersonId());
                idTypeMap.put(cppm.getPersonId(),cppm.getPersonType());

                //
                ProjectPerson ss = projectPersonService.selectProjectPersonByPersonId(cppm.getPersonId());
                if(ss!=null){
                    ProjectPerson pp = new ProjectPerson();
                    pp.setPersonType(DictUtils.getDictLabel("pm_person_type",cppm.getPersonType()));
                    pp.setPersonName(ss.getPersonName());
                    pp.setLocked(cppm.getLocked());
                    projectPersonList.add(pp);
                }

            });
            bidProject.setProjectPersonList(projectPersonList);
        }
        bidProject.setTypePersonList(projectPersonService.getCascaderList());
        return AjaxResult.success(bidProject);
    }

    /**
     * 获取基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:query')")
    @GetMapping(value = "/appInfo/{projectId}")
    public AjaxResult appInfo(@PathVariable("projectId") Long projectId)
    {
        BidProject bidProject= myBidProjectService.selectBidProjectByProjectId(projectId);
        List<ProjectPerson>projectPersonList = new ArrayList<>();
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){

            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                //TODO 修改点
                ProjectPerson ss = projectPersonService.selectProjectPersonByPersonId(cppm.getPersonId());
                if(ss!=null){
                    ProjectPerson pp = new ProjectPerson();
                    pp.setPersonType(DictUtils.getDictLabel("pm_person_type",cppm.getPersonType()));
                    pp.setPersonName(ss.getPersonName());
                    pp.setLocked(cppm.getLocked());
                    projectPersonList.add(pp);
                }

            });
        }
        bidProject.setProjectPersonList(projectPersonList);
        //查询出所有步骤，查询出运行了步
        BidProjectPoint bppCondition = new BidProjectPoint();
        bppCondition.setProjectId(projectId);
        List<BidProjectPoint>bbpList =  bidProjectPointService.selectBidProjectPointList(bppCondition);

        BidProjectProcess processCondition = new BidProjectProcess();
        processCondition.setProjectId(projectId);
        List<BidProjectProcess>processList =  bidProjectProcessService.selectBidProjectProcessList(processCondition);

//        if(bbpList!=null && bbpList.size()>bidProject.getCurrentBidStep()){
//            if(processList==null) {
//                processList = new ArrayList<>();
//            }
//            for(int i=bidProject.getCurrentBidStep();i<bbpList.size();i++){
//                BidProjectProcess newProcess = new BidProjectProcess();
//                newProcess.setPointName(bbpList.get(i).getPointName());
//                newProcess.setStep(0);
//                processList.add(newProcess);
//            }
//        }
        if(bbpList!=null){
            bbpList.forEach(bbp->{
                bbp.setName(bbp.getPointName());
            });
        }
        bidProject.setBidProjectPointList(bbpList);

        return AjaxResult.success(bidProject);
    }

    /**
     * 新增基本信息
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:add')")
    @Log(title = "基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BidProject bidProject)
    {
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){
            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    cppm.setPersonType(selectedPerson.get(0));
                    cppm.setPersonId(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }
        return toAjax(myBidProjectService.insertBidProject(bidProject));
    }


    //选择“锁定”复选框后，在保存时，进行判断验证，验证条件：所有锁定人员依次在投标项目和业绩（历史）项目中判断是否存在已被锁定情况，
//若已锁定则弹出“项目人员名称+“已在投标项目”+项目名称中被锁定，请先解锁！”提醒信息（存在多个人员被锁定情况，就一起将提醒信息显示）
    @PostMapping(value = "/otherProjectPerson")
    public AjaxResult otherProjectPerson(@RequestBody BidProject bidProject)
    {
        List<Long>personIds = new ArrayList<>();
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){
            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    personIds.add(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }

        StringBuilder sb =new StringBuilder();
        if(personIds!=null && personIds.size()>0){

            List<ProjectPerson> personList = projectPersonService.selectOtherProjectProject(personIds,bidProject.getProjectId());
            //2.查看历史表占用
            List<ProjectPerson> personCurrentList = projectPersonService.selectOtherCurrentProject(personIds,bidProject.getProjectId());
            if((personList!=null&& personList.size()>0)){
                personList.forEach(person->{
                    sb.append(person.getPersonName()+"已在投标项目"+person.getProjectName()+"中被锁定，请先解锁！").append("\n");
                });
            }
            if(personCurrentList!=null && personCurrentList.size()>0){
                personCurrentList.forEach(person->{
                    sb.append(person.getPersonName()+"已在现有项目"+person.getProjectName()+"中被锁定，请先解锁！").append("\n");
                });
            }
        }

        if(sb.length()>0){
            return AjaxResult.success(sb.toString());
        }else {
            return AjaxResult.success();
        }
    }

    @PostMapping(value = "/otherProjectPerson_old")
    public AjaxResult otherProjectPersonOld(@RequestBody BidProject bidProject)
    {
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){
            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    cppm.setPersonType(selectedPerson.get(0));
                    cppm.setPersonId(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }
        //搜索出 //安全员c 技术负责人k 一级建造师l 二级建造师m
        StringBuilder sb = new StringBuilder();
        /*List<String>types = new ArrayList<>(4);
        types.add("c");
        types.add("k");
        types.add("l");
        types.add("m");*/
        List<BidProjectPresonMap> condition = bidProject.getBidProjectPresonMapList();
        /*if(bidProjectPresonMapList!=null){
            condition = bidProjectPresonMapList.stream().filter(person->types.contains(person.getPersonType())).collect(Collectors.toList());
        }*/

        /*if(condition!=null && condition.size()>0){
            condition.forEach(bpm->{
                //1.查看投标表占用
                bpm.setBidDate(bidProject.getEstimatedBidTime());
                List<ProjectPerson> personList = projectPersonService.selectOtherProjectProject(bpm);
                //2.查看历史表占用
                List<ProjectPerson> personCurrentList = projectPersonService.selectOtherCurrentProject(bpm);
                if((personList!=null&& personList.size()>0)){
                    sb.append(personList.get(0).getPersonName()+" ");
                }else if(personCurrentList!=null && personCurrentList.size()>0){
                    sb.append(personCurrentList.get(0).getPersonName()+" ");
                }
            });
        }*/

        if(sb.length()>0){
            return AjaxResult.success(sb.toString()+"已经在其他项目占用");
        }else {
            return AjaxResult.success();
        }
    }

    /**
     * 修改基本信息
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:edit')")
    @Log(title = "基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BidProject bidProject)
    {
        if(bidProject!=null && bidProject.getBidProjectPresonMapList()!=null
                && bidProject.getBidProjectPresonMapList().size()>0){

            List<BidProjectPresonMap>list = bidProject.getBidProjectPresonMapList().stream().filter(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();

                return selectedPerson!=null && selectedPerson.size()==2 &&
                        selectedPerson.get(0)!=null && selectedPerson.get(0).trim().length()>0&&
                        selectedPerson.get(1)!=null && selectedPerson.get(1).trim().length()>0;
            }).collect(Collectors.toList());

            bidProject.setBidProjectPresonMapList(list);
            bidProject.getBidProjectPresonMapList().forEach(cppm->{
                List<String> selectedPerson = cppm.getSelectedPerson();
                if(selectedPerson!=null && selectedPerson.size()>0){
                    cppm.setPersonType(selectedPerson.get(0));
                    cppm.setPersonId(Long.parseLong(selectedPerson.get(1)));
                }
            });
        }
        return toAjax(myBidProjectService.updateBidProject(bidProject));
    }

    /**
     * 删除基本信息
     */
    @PreAuthorize("@ss.hasPermi('business:my_bid_project:remove')")
    @Log(title = "基本信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds)
    {
        return toAjax(myBidProjectService.deleteBidProjectByProjectIds(projectIds));
    }
}
